<template>
	<div class="container add_edit">
		<el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
			<el-form-item label="活动名称" prop="name" ref="name">
				<el-input v-model="form.name" placeholder="请输入活动名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="活动时间" prop="activityTime" ref="activityTime">
				<el-date-picker v-model="form.activityTime" type="datetimerange" align="right" range-separator="至"
					start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerTimeOptions" class="time">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="排序">
				<el-input type="number" v-model.number="form.sort" :min="1" placeholder="请输入排序" clearable
					oninput="value = parseInt(value) || 1"></el-input>
			</el-form-item>
			<el-form-item label="备注">
				<el-input v-model="form.remark" placeholder="请输入备注" clearable></el-input>
			</el-form-item>
			<el-form-item label="状态">
				<el-switch v-model="form.state" active-color="#ff6a6c" inactive-color="#bbb" active-value="启用"
					inactive-value="禁用"></el-switch>
			</el-form-item>
			<el-form-item label="秒杀商品" prop="goods_objs" ref="goods_objs">
				<el-button round icon="el-icon-plus" class="addGoods-btn" @click="addGoods"></el-button>
				<el-button v-if="form.goods_objs.length > 0" round icon="iconfont iconbianji" class="addGoods-btn"
					@click="editGoods"></el-button>
			</el-form-item>
			<el-form-item v-if="form.goods_objs.length > 0">
				<div class="dflex_wrap">
					<el-card :body-style="{ padding: '0px' }" shadow="hover"
						class="card margin_b_10 padding_10 padding_t_20 pos_r margin_r_15 crpr"
						v-for="(item, i) in form.goods_objs" :key="i">
						<use-carousel :width="150" :height="150" :imgs="item.imgs" :video="item.video"></use-carousel>
						<div class="card_bottom pos_a">
							<el-popover :open-delay="350" :close-delay="80" placement="top" trigger="hover"
								:content="item.name">
								<div slot="reference" class="name pos_a ellipsis crpr padding_lr_10 sele_none">
									{{ item.name }}
								</div>
							</el-popover>
							<div class="price pos_a sele_none">{{ item.price / 100 }}</div>
							<div class="m_price pos_a sele_none">{{ item.market_price / 100 }}</div>
						</div>
						<div class="el-icon-close crpr pos_a" @click="goodsRemove(i)"></div>
					</el-card>
				</div>
			</el-form-item>
			<el-form-item>
				<el-button :loading="formLoading" round icon="el-icon-check" class="confirm-btn"
					@click="submitForm('ruleForm')">提交</el-button>
				<el-button round icon="el-icon-back" class="return-btn" @click="returnPage">返回</el-button>
			</el-form-item>
		</el-form>
		<goods ref="goodsRef" @choiceGoods="getGoodsDatas"></goods>
		<el-drawer title="添加秒杀商品" size="500px" class="seckill_drawer" :visible.sync="seckillDrawer" direction="rtl"
			:append-to-body="true" :wrapperClosable="false">
			<div style="height: 90%; overflow: overlay;">
				<div class="seckill_goods" v-for="(item, i) in goodsDatas" :key="i">
					<div class="dflex_vertical_c">
						<use-carousel :width="84" :height="84" :imgs="item.imgs" :video="item.video"></use-carousel>
						<div class="left_just margin_l_20">
							<el-popover :open-delay="350" :close-delay="80" placement="top" trigger="hover"
								:content="item.name + ''">
								<div slot="reference" class="ellipsis crpr">{{ item.name }}</div>
							</el-popover>
							<el-popover :open-delay="350" :close-delay="80" placement="top" trigger="hover"
								:content="item.name_pw">
								<div slot="reference" class="ellipsis crpr">{{ item.name_pw }}</div>
							</el-popover>
						</div>
					</div>
					<el-form :model="item" ref="seckillRuleForm" :rules="rules" label-width="90px"
						class="add_edit margin_t_20">
						<el-form-item label="秒杀价" prop="price" ref="price">
							<el-input v-model.number="item.price" placeholder="请输入秒杀价" type="number" :min="0" clearable
								oninput="value = parseInt(value)">
							</el-input>
							<div class="remark_txt">{{ item.price || 0 }} 分 = {{ item.price / 100 }} 元</div>
						</el-form-item>
						<el-form-item label="库存" prop="stock_num" ref="stock_num">
							<el-input v-model.number="item.stock_num" placeholder="请输入库存" type="number" :min="0"
								clearable oninput="value = parseInt(value)"></el-input>
						</el-form-item>
						<el-form-item label="限购量" prop="limit" ref="limit">
							<el-input v-model.number="item.limit" placeholder="请输入限购量" type="number" :min="0" clearable
								oninput="value = parseInt(value)">
							</el-input>
							<div class="remark_txt">一位用户允许秒杀的次数</div>
						</el-form-item>
					</el-form>
				</div>
				<div class="btn pos_a">
					<el-button round icon="el-icon-check" class="confirm-btn" @click="seckillData('seckillRuleForm')">提交
					</el-button>
					<el-button round icon="el-icon-back" class="return-btn" @click="seckillDrawer = false">取消
					</el-button>
				</div>
			</div>
		</el-drawer>
	</div>
</template>

<script>
	const __name = 'wmzmall-market-seckill';
	export default {
		data() {
			const validateGoodsObjs = async (rule, value, callback) => {
				if (value.length <= 0) {
					return callback(new Error('请选择秒杀商品'));
				}

				callback();
			};
			return {
				dataId: '',
				formLoading: false,
				form: {
					name: '',
					activityTime: [],
					seckill_begin_time: '',
					seckill_end_time: '',
					sort: 0,
					remark: '',
					state: '启用',
					goods_ids: [],
					goods_objs: []
				},
				pickerTimeOptions: {
					disabledDate(time) {
						return time.getTime() < Date.now() - 3600 * 1000 * 24;
					},
					shortcuts: [{
							text: '最近一周',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
								picker.$emit('pick', [end, start]);
							}
						},
						{
							text: '最近一个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
								picker.$emit('pick', [end, start]);
							}
						},
						{
							text: '最近三个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
								picker.$emit('pick', [end, start]);
							}
						}
					]
				},
				rules: {
					name: [{
						required: true,
						message: '请输入活动名称',
						trigger: 'change'
					}],
					activityTime: [{
						type: 'array',
						required: true,
						message: '请选择活动时间',
						trigger: 'change'
					}],
					goods_objs: [{
						type: 'array',
						required: true,
						validator: validateGoodsObjs,
						trigger: 'change'
					}],
					price: [{
						required: true,
						message: '请输入秒杀价格',
						trigger: 'change'
					}],
					stock_num: [{
						required: true,
						message: '请输入库存',
						trigger: 'change'
					}],
					limit: [{
						required: true,
						message: '请输入限购量',
						trigger: 'change'
					}]
				},
				goodsDatas: [],
				seckillDrawer: false
			};
		},
		watch: {
			'form.goods_objs'(val) {
				if (val.length <= 0) {
					this.$refs.ruleForm.validateField('goods_objs');
				} else {
					this.$refs.goods_objs.clearValidate();
				}
			}
		},
		methods: {
			async loadData() {
				if (!this.dataId) {
					this.$db[__name].getsort().then(res => {
						if (res.code == 200) {
							this.form.sort = ++res.datas.sort;
						}
					});
					return;
				}

				await this.$db[__name].tofirst(this.dataId).then(res => {
					if (res.code == 200) {
						for (let item in this.form) {
							this.form[item] = res.datas[item];
						}

						this.form.activityTime = [];
						this.form.activityTime.push(res.datas.seckill_begin_time);
						this.form.activityTime.push(res.datas.seckill_end_time);
					}
				});
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.formLoading = true;
						if (this.form.activityTime && this.form.activityTime.length > 0) {
							if (this.form.activityTime[0] == this.form.seckill_begin_time && this.form
								.activityTime[1] == this.form.seckill_end_time) {
								this.form.activityTime[0] = new Date(this.form.activityTime[0]);
								this.form.activityTime[1] = new Date(this.form.activityTime[1]);
							}
							this.form.seckill_begin_time = this.form.activityTime[0].getTime();
							this.form.seckill_end_time = this.form.activityTime[1].getTime();
						}

						delete this.form.activityTime;

						if (!this.dataId) {
							this.$db[__name].add(this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						} else {
							this.$db[__name].update(this.dataId, this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						}
					}
				});
			},
			addGoods() {
				this.$refs.goodsRef.show({
					_id: this.$db.$cmd.nin(this.form.goods_ids),
					state: '销售中'
				});
			},
			editGoods() {
				this.goodsDatas = this.form.goods_objs;
				this.seckillDrawer = true;
			},
			getGoodsDatas(datas) {
				datas.forEach(x => {
					x.market_price = x.price;
					x.stock_num = '';
					x.limit = 1;
				});

				this.goodsDatas = datas;
				this.seckillDrawer = true;
			},
			seckillData(formName) {
				let _valid = true;
				for (var i = 0; i < this.$refs[formName].length; i++) {
					this.$refs[formName][i].validate((valid, obj) => {
						if (!valid) {
							let __obj = this.$api.get_form_prop(obj);

							this.$refs[__obj][i].$el.querySelector('input').focus();
							this.$refs[__obj][i].$el.querySelector('input').click();
							this.$refs[__obj][i].$el.scrollIntoViewIfNeeded(true);
							_valid = false;
							return;
						}
					});
					if (!_valid) {
						return false;
					}
				}
				if (_valid) {
					this.form.goods_ids = [];
					this.form.goods_objs = [];

					this.goodsDatas.forEach(x => {
						this.form.goods_ids.push(x._id);
						this.form.goods_objs.push(x);
					});
					this.seckillDrawer = false;
				}
			},
			goodsRemove(i) {
				this.form.goods_ids.splice(i, 1);
				this.form.goods_objs.splice(i, 1);
			},
			returnPage() {
				uni.$emit('closeTab');
				uni.redirectTo({
					url: '/pages/marketing/seckill/limit_seckill'
				});
			}
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.loadData();
		}
	};
</script>

<style>
	.seckill_drawer .add_edit .el-input {
		width: 80%;
	}

	.seckill_drawer .el-drawer__header {
		background-color: #f5f5f5;
		padding-bottom: 32px;
	}

	.seckill_drawer .el-drawer__body {
		background-color: #f5f5f5;
	}

	.seckill_drawer .sele {
		width: 80%;
	}

	.seckill_drawer .sele>>>.el-input {
		width: 100%;
	}

	.seckill_goods {
		padding: 20px;
		background-color: #fff;
		margin: 16px;
		border-radius: 10px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.seckill_goods .ellipsis {
		width: 300px;
	}

	.btn {
		bottom: 20px;
		right: 20px;
	}

	.addGoods-btn:hover,
	.addGoods-btn:focus {
		color: #ff6a6c;
		border-color: #ff6a6c;
		background-color: #fff;
	}

	.card {
		border-radius: 10px;
		overflow: hidden;
	}

	.card .img {
		transition: transform 1s;
	}

	.card:hover .img {
		transform: scale(1.08);
	}

	.card .card_bottom {
		left: 0;
		right: 0;
		bottom: 0;
		color: #fff;
		width: 100%;
		height: 70px;
		text-align: center;
		background-color: rgba(0, 0, 0, 0.4);
		z-index: 999;
	}

	.card_bottom .name {
		top: 0;
		font-size: 16px;
	}

	.card_bottom .price {
		top: 20px;
		left: 50%;
		transform: translate(-50%, 0);
		color: #fff;
		font-size: 14px;
	}

	.card_bottom .m_price {
		top: 36px;
		left: 50%;
		transform: translate(-50%, 0);
		color: #fff;
		font-size: 14px;
	}

	.card .ellipsis {
		width: 100%;
	}

	.card .el-icon-close {
		right: 4px;
		top: 4px;
	}

	.card .el-icon-close:hover {
		color: #ff6a6c;
	}
</style>
